Repository navigation
Conversation
|
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
coderdan
left a comment
There was a problem hiding this comment.
This is an automated code review, run at the PR author's request.
Summary. The scalar mapping is vitaminc's from end to end. The addon reads each value with JsRef::to_frame and builds each result with JsBuilder. Every value is sealed by the engine through one Vec<_>::encrypt_into, and the counting key source really checks one generate and one retrieve for three values. I found no lossy scalar conversion. -0, NaN, Infinity, the i128 bounds, year 0001, and a JS 42n (sealed as i8) all round-trip, and Rust's decrypt::<i64> and decrypt::<Timestamp> open what the SDK seals. The problems are in the JSON path, in some error kinds, and in one interface check. Nothing is blocking.
Blocking
None.
Should fix
- A JSON document nested 128 levels deep fails on encrypt with kind
open, codestack_encrypt::aead, and a message saying the ciphertext is damaged or was altered (crates/core/src/json.rs:70). - A stored JSON document read back with
fromBytesopens as its JSON text. The obvious next step,JSON.parse, silently loses the digits thebigintrule protects (src/cipher.ts:48,README.md:52). - Every float of 2^53 or more is refused in a JSON document, because such a float has no fraction. A document Rust wrote with
1e20opens in JS, and encrypting it again is refused (crates/core/src/json.rs:146). - A JSON document with a
constructor,prototypeor__proto__key cannot be encrypted, and one written by another SDK opens as aninternalerror (crates/core/src/json.rs:79). - The native
encryptanddecryptchanged shape, butBINDING_INTERFACEis still 1, so a stale step-1recipher.nodeis accepted (src/native.ts:25). - A
VcUuidis refused with a message that does not mention a UUID (src/cipher.ts:291). - Tests. The engine-seals, SDK-opens direction is tested only for a string (
crates/core/tests/round_trip.rs). Add cases where the engine seals ani64,u64::MAX, aTimestamp, aDecimal, bytes and aJsonPlaintextholdingu64::MAX, and the SDK opens each one. Without them, the claim that both sides read each other holds for text only. Separately, the "with vitaminc's code" test does not check the code (__tests__/addon/values.test.ts:217).
Question / design
- When the addon is missing, constructing a wrapper class throws. The classes are also built at import time, so the addon now loads when the package is imported (
src/values.ts:85).
Nit
- A JSON map key copied in Rust is not wiped when its value is refused (
crates/core/src/json.rs:285). - The docs say a
bigintin a document "is written as its digits". They do not say that one outside the 64-bit range is refused (src/values.ts:119). - A top-level typed array other than
Uint8Array, such as aUint16Array, is refused asrecipher::plain_objectwith "wrap it in json(..)".json(..)refuses it too. Only the message is wrong (src/cipher.ts,refuse).
What I ran. I built the debug addon (build:debug) and ran test:addon: 35 passed. I also ran throwaway probes, deleted afterwards. In Rust (cargo test --all-features), the SDK sealed an i8 and a millisecond timestamp, and the engine opened them as i64 and Timestamp. I checked JSON depths 126 to 129, re-encrypted an engine-sealed {"x": 1e20}, and round-tripped NaN, Infinity and -0. In vitest I checked each refusal's kind and code, json(..) with large floats, sparse arrays, lone surrogates and the prototype keys, Dates at the range ends, and fromBytes of a JSON ciphertext. CI is green.
| } | ||
|
|
||
| /// The document a frame holds, as the engine's [`JsonPlaintext`]. | ||
| pub(crate) fn document(frame: &ValueFrame) -> Result<JsonPlaintext, Refusal> { |
There was a problem hiding this comment.
Should fix: a document that is too deep fails on encrypt as open / stack_encrypt::aead.
vitaminc lets a frame nest 128 levels. The engine's JSON parser reads 127. So keyset.encrypt(json(deep)) with 128 nested arrays passes document(). Then JsonPlaintext's visit refuses it as Error::Aead, and Refusal::engine maps that to kind open. What comes back is:
{ kind: 'open', code: 'stack_encrypt::aead',
message: 'AEAD operation failed (wrong key, AAD mismatch, or malformed ciphertext). ... the ciphertext is damaged or was altered.' }
That is wrong on an encrypt. A caller switching on kind would treat it as tampering. I reproduced this from vitest and from Rust: depths 126 and 127 seal, 128 fails as above, and 129 is refused by vitaminc.
Fix: check the depth here, at most 127 as the engine's parser reads, and refuse with recipher::not_json ("nested deeper than 127 levels"). You could also make encrypt_with map an engine Aead to Kind::Value, since no ciphertext exists yet. Add a test at 127 and 128.
There was a problem hiding this comment.
Fixed in the rewrite (fc5c851). The bridge checks the depth when json(..) reads the document, at most 127 levels (crate/src/json.rs:33-39). A deeper document is recipher_js::too_deep, not an engine Aead error. seal also maps an engine Aead error on encrypt to recipher_js::not_sealed (crate/src/cipher.rs:399-404), because no ciphertext exists yet.
Tests: 127 and 128 levels at __tests__/addon/values.test.ts:538-552, and the parser's limit at crate/src/json.rs:206-210. Errors no longer have a kind, so a caller switches on the code.
| * decrypting is what authenticates them. | ||
| * | ||
| * A JSON document is sealed as its JSON text, so one read back here | ||
| * opens as that text. |
There was a problem hiding this comment.
Should fix: the untyped fromBytes gap is a trap for JSON.
The real path is store, then read back, so in practice every json(..) value goes through fromBytes and opens as a string. The natural next step loses data silently. I ran:
const sealed = (await k.encrypt(json({ id: 18446744073709551615n }))).unwrap()
const opened = (await c.decrypt(Ciphertext.fromBytes(sealed.toBytes()).unwrap())).unwrap()
// opened === '{"id":18446744073709551615}'
JSON.parse(opened) // { id: 18446744073709552000 }This is the precision loss the bigint rule exists to prevent. The type is honest (OpenedScalar includes string), but nothing pushes the caller to the right reader, because none exists yet.
Fix: add a way to read stored bytes as a JSON document in this PR, for example Ciphertext.fromBytes(bytes, { json: true }), to become kinds.json in step 3. Or keep json(..) back until typed fromBytes lands. At the very least, say in this doc comment and the README not to JSON.parse the text.
There was a problem hiding this comment.
Fixed in the rewrite (fc5c851). Ciphertext.fromBytes(bytes, kinds.json) reads stored bytes as a JSON document (src/kinds.ts:52, crate/src/ciphertext.rs:80-86). The fromBytes doc (crate/src/ciphertext.rs:96-103) and README.md:150-155 say that with no kind a document decrypts as its text. Both also say that JSON.parse of that text loses digits.
Test: __tests__/addon/values.test.ts:388-404 reads stored bytes with kinds.json, and gets 18446744073709551615n back.
| | `new VcDate('2026-11-23')` | a calendar date | `VcDate` | | ||
| | `new VcDecimal('1.50')` | a decimal, with its scale | `VcDecimal` | | ||
| | `null` | null | `null` | | ||
| | `json(value)` | a JSON document, as its JSON text | the document | |
There was a problem hiding this comment.
"Decrypts as: the document" is true only for a Ciphertext that never left memory. Read back with Ciphertext.fromBytes, which is how stored data is read, it decrypts as the JSON text, and JSON.parse of that text loses bigint digits. See the comment on src/cipher.ts:48. Please make this row say so, or fix the gap.
There was a problem hiding this comment.
Fixed. The row at README.md:67 now says a document decrypts as the document from the Ciphertext that encrypt returned, or from one read with kinds.json. README.md:150-155 covers bytes read back from storage.
| return Ok(Value::Number(Number::from(value as i64))); | ||
| } | ||
| return Err(NotJson::Kind( | ||
| "an integer outside the safe range held as a number; use a bigint", |
There was a problem hiding this comment.
Should fix: every large float is refused, and decrypt then encrypt fails.
Every f64 of magnitude 2^53 or more has no fraction. So this branch refuses every large float, not only integers that lost digits. json({ x: 1e21 }), json({ x: Number.MAX_VALUE }) and json(JSON.parse('{"x":6.02e23}')) are all recipher::not_json.
Worse, the read and write rules disagree. A document Rust or Go wrote as {"x": 1e20} opens in JS as { x: 1e20 }, a number (number_of returns F64). Encrypting that same value again is refused. I checked this in Rust: the engine sealed JsonPlaintext::from(json!({"x": 1e20})), the SDK opened it with Encoding::Json, and re-sealing it gave Err(Value, "recipher::not_json", "...an integer outside the safe range held as a number; use a bigint").
Fix: write an integer-valued float outside the safe range as a float. Number::from_f64(1e20) writes 1e20, and the engine's parser reads it back as the same float. Or narrow the refusal to the range where an integer was plausibly meant (for example, up to 2^64). Then add a test that decrypts a document and encrypts it again.
There was a problem hiding this comment.
Mostly fixed, with one gap. The refusal is narrowed to a whole number from 2^53 up to 2^64 (value-napi/src/scalar.rs:139-152). A larger whole number is stored as a float. So 1e20, Number.MAX_VALUE, and 6.02e23 encrypt, decrypt, and encrypt again (__tests__/addon/values.test.ts:555-569).
The gap is a float from 2^53 up to 2^64 that another SDK wrote, such as 1e18. The engine reads 1e18 as a float, so it decrypts as a number. Encrypting that number again is refused. This gap comes from reading the code, and has not been run. No test or doc covers it.
The choice is between documenting the gap with a test, and writing such a number as a float, as the review first suggested.
|
|
||
| /// The value of an opened document's text, as a frame, by the rules in the | ||
| /// module docs. | ||
| pub(crate) fn opened(frame: &ValueFrame) -> Result<ValueFrame, Refusal> { |
There was a problem hiding this comment.
Should fix: JSON keys constructor, prototype and __proto__.
vitaminc refuses these three property names in both directions. For a record that is a fine rule. In a JSON document they are ordinary keys (JSON.parse('{"constructor":1}') gives an own property). What happens now:
keyset.encrypt(json(JSON.parse('{"constructor":1}')))gives{ kind: 'value', code: 'InvalidArg', message: 'the value could not be read for encryption' }. The code is a napi status, not a stable one, and the message does not say why.- A document another SDK wrote with such a key gives
{ kind: 'internal', code: 'recipher::build_value' }on decrypt.internalmeans "not the caller's to fix", but the data is authentic and simply cannot be built in JS.
I reproduced both. For the decrypt case I sealed the text as a string and opened it with the JSON encoding, which is the same leaf the engine seals.
Fix: decide with vitaminc how a JSON document carries these keys. Until then, report kind open on decrypt and value on encrypt, with a code that names the key rule, and list the three keys in the README.
There was a problem hiding this comment.
Partly. Both directions now give recipher_js::reserved_key (value-napi/src/error.rs:25, crate/src/js.rs:149-156). The code names the rule.
README.md:88 and README.md:146-149 list the three names, and say a document from another SDK with one of them does not decrypt here. Test: __tests__/addon/values.test.ts:571-588, both ways. Errors no longer have a kind.
Still open: the SDK still cannot encrypt or decrypt a document that contains one of these keys. Nobody has decided how the SDK should handle such a document.
| value instanceof VcDate || | ||
| value instanceof VcTimestamp || | ||
| value instanceof VcDecimal || | ||
| value instanceof VcUuid |
There was a problem hiding this comment.
Should fix: the UUID refusal does not say "UUID".
A VcUuid passes this check and is refused later, by the engine's value model. The result is:
{ kind: 'value', code: 'recipher::value',
message: 'the value cannot be encrypted: expected a null, bool, integer, float, string, bytes, date, timestamp or decimal in range' }
A caller who reads the README will look for a UUID message and not find one. Since the SDK exports the class and knows it cannot be sealed, refuse it here with its own code, for example recipher::uuid and "a UUID cannot be encrypted yet: the engine's value model does not hold one". Assert that code in the values.test.ts UUID test, which checks only the kind today.
There was a problem hiding this comment.
Fixed in the rewrite (fc5c851). An RcUuid gets its own code, recipher_js::uuid, with help to encrypt it as a string (crate/src/js.rs:55-57, crate/src/error.rs:46). The test asserts the code, and that the message says UUID (__tests__/addon/values.test.ts:644-651). The pull request #1996 later removes the refusal, when the SDK can encrypt a UUID.
| expect(result.err()?.kind).toBe('value') | ||
| }) | ||
|
|
||
| it("an integer vitaminc cannot hold, with vitaminc's code", async () => { |
There was a problem hiding this comment.
The test name promises vitaminc's code, but the test asserts only kind and the message. Today the code is ERR_INTEGER_RANGE (I checked), so add expect(result.err()?.code).toBe('ERR_INTEGER_RANGE'). Without it, a regression to a generic code would still pass.
There was a problem hiding this comment.
Fixed. The test now asserts the code, ERR_INTEGER_RANGE, and that the message does not contain the value (__tests__/addon/values.test.ts:653-659).
| const message = binding.error.message | ||
| const Missing = class { | ||
| constructor(_text: string) { | ||
| throw new TypeError(`${name} needs the native build: ${message}`) |
There was a problem hiding this comment.
Question / design: a missing addon throws here.
The plan says nothing escapes as an exception, and that a build that does not load is an Err. With this stand-in, new VcDate('2026-11-23') throws a TypeError when the addon is missing. It is the only SDK call that does. An alternative: a frozen stand-in that keeps its text and constructs normally. Then the failure arrives at keyset.encrypt(..), which already returns recipher::load without a build. Is the throw deliberate?
Related: wrapperClass calls native() at module load (line 78), so the addon is now loaded when the package is imported. native.ts still says it is "loaded once, on first use". Either make it lazy, or update that comment.
There was a problem hiding this comment.
Fixed. A stand-in wrapper class now constructs from a string, as the real class does (src/values.ts:73-97, last changed in dab69c5). Both throw a TypeError only for an argument that is not a string, and README.md:199-202 says so. With no addon, the failure then comes from encrypt, as recipher_js::load. __tests__/addon/builds.test.ts:75-76 tests this case.
The addon now loads when the package is imported, and the docs say so: src/binding.ts:19 and :133, and README.md:288.
| fn entry(&mut self, key: &str) -> Result<ToJson<Member<'_>>, NotJson> { | ||
| Ok(ToJson(Member { | ||
| object: &mut self.members, | ||
| key: key.to_owned(), |
There was a problem hiding this comment.
Nit: hygiene. This key copy is wiped only when it reaches the map. If the member's value is refused (bytes, a date, an unsafe float), ToJson<Member> is dropped with the key in it, and the key is freed without being wiped. The same happens when the member holds an array or object that is dropped unfinished: the Member sits in out and is dropped without a wipe. Holding the key in Zeroizing<String> until put would fix both.
There was a problem hiding this comment.
No longer applies. The addon's JSON walk is gone (e0cc1c6), and the key copy went with it. The bridge now writes the JSON text straight into a Buffer that wipes each allocation it outgrows (value-napi/src/json.rs:18-21). Each key the bridge reads is a Zeroizing<String> (value-napi/src/js.rs:66-69).
| /** | ||
| * A JSON value. An integer outside the safe range of a `number` is a | ||
| * `bigint`; on encrypt, a `number` that is an integer outside it is | ||
| * refused, and a `bigint` is written as its digits. |
There was a problem hiding this comment.
Nit. "A bigint is written as its digits" does not mention the limit. A bigint outside the 64-bit range (below i64::MIN or above u64::MAX) is refused, because the engine's parser reads no wider. Please say so here and in the README.
There was a problem hiding this comment.
Fixed. The docs give the range, from -(2n ** 63n) to 2n ** 64n - 1n, and say a bigint outside the range is refused. The range is in crate/src/json.rs:137-138, src/values.ts:165-168, README.md:125-126, and README.md:135. napi copies the Rust doc to native.d.ts:266-267. The test is at __tests__/addon/values.test.ts:424.
There was a problem hiding this comment.
Finished in 89a3b27. The earlier reply said src/values.ts gives the range, but that doc said only "within 64 bits". The doc now gives the range, from -(2n ** 63n) to 2n ** 64n - 1n, and says a bigint outside it is refused. The Rust doc and the README already said this.
44064c7 to
a94a1a7
Compare
2232e04 to
845303d
Compare
845303d to
872ff2e
Compare
a94a1a7 to
30f1d26
Compare
872ff2e to
4046495
Compare
a251427 to
a5555b7
Compare
The skeleton encrypts one string. An application needs every value JavaScript has, arrays of them, and JSON documents. keyset.encrypt now takes every value in the value bridge's mapping: a string, a boolean, a number, a bigint at the narrowest width that holds it, bytes, a Date, the wrapper classes for a date, a fine timestamp and a decimal, and null. An array in gives an array out, in one key request each way, and one refused element fails the whole array before any request. json(..) is a native function that reads a document when it is called and holds the engine's JsonPlaintext, so a document is encrypted as the engine encrypts one. A Ciphertext records the kind it decrypts as, and Ciphertext.fromBytes(bytes, kind) reads stored bytes as a kind, so a JSON document read back with kinds.json decrypts to the document, not to its text. Each refusal is a variant of the SDK's error enum with a recipher_js:: code of its own, and the bridge's refusals keep the bridge's codes. Every new signature is written on the Rust method, as the skeleton's are: the array overloads of encrypt and decrypt, and the kind overload of fromBytes, are ts_type strings, one overload per line, so the generated native.d.ts stays the public type. The value types those signatures name live in src/value-types.ts, which imports nothing: the declarations import it, and a module that loaded the addon would make them import themselves. A Json is the native class, marked in the header so no other object type-checks as one. A ciphertext with no type named now allows any scalar, since one read from stored bytes with no kind can decrypt to any. Nothing is released, so the binding interface stays 1. Closes #1812
a5555b7 to
fc5c851
Compare
| if value.get_type().ok() == Some(ValueType::Undefined) { | ||
| return Err(Error::Undefined.into()); | ||
| } | ||
| let uuid = is_uuid(env, &value); |
There was a problem hiding this comment.
Why is there a special case for UUID?
There was a problem hiding this comment.
Not removed in this PR yet. The check is at crate/src/js.rs:55-57, and the pull request #1996 deletes it.
The engine accepts a UUID now, but this PR does not. The uuid kind (#1929) reached this branch when next was merged in (85c1fc8). This PR has no kinds.uuid and no UUID round-trip test. The TypeScript types in this PR say an RcUuid is not a Scalar. Without the check, encrypt would store a value that those types refuse.
The pull request #1996 adds the kind, the types, and the tests. The same pull request removes the check.
Four places are out of date. Each says the engine has no UUID type: README.md:79-81, src/values.ts:134-140, src/value-types.ts:36-40, and the test name at __tests__/addon/values.test.ts:644. Each should say that this PR does not take a UUID yet.
| .map_err(|error| refused(env, &error))?; | ||
| ValueFrame::from_bytes(frame.as_protected_ref()).map_err(|_| Error::Value.into()) | ||
| ValueFrame::from_bytes(frame.as_protected_ref()) | ||
| .map_err(|_| RecipherErrorFields::from(if uuid { Error::Uuid } else { Error::Value })) |
There was a problem hiding this comment.
That's a nasty hack.
There was a problem hiding this comment.
Partly fixed. The flag that chose the error code after a failed read is gone (merge 85c1fc8). An RcUuid is now refused by a direct check before the walk, at crate/src/js.rs:55-57.
The check is still a special case, and the pull request #1996 removes it. The reply to the question about the UUID special case says why the check is still here.
| .to_frame() | ||
| .map_err(|error| refused(env, &error))?; | ||
| ValueFrame::from_bytes(frame.as_protected_ref()).map_err(|_| Error::Value.into()) | ||
| ValueFrame::from_bytes(frame.as_protected_ref()) |
There was a problem hiding this comment.
The code in this method seems to be doing multiple conversions from a JS ref to a frame and then to a value frame. There are several layers of indirection here.
I would have thought that the napi crate did all of this already directly from the unknown type into our value types.
There was a problem hiding this comment.
Partly. The value is converted once. One extra layer is already gone. One more goes with #2011. Two more could go.
The path today, for keyset.encrypt(value) at 1cf2f55:
- napi passes the argument as
Unknown(crate/src/cipher.rs:174-178). The argument has no fixed type because it can be one value, an array of values, or aJson. js::elements(crate/src/js.rs:99-135) checks for an array, and reads each element as an own property.one_value(crate/src/cipher.rs:379-384) sends aJsonto the JSON path, and any other value tojs::read.JsRef::to_frame(crate/src/js.rs:58-60) is the one conversion. The bridge walks the JavaScript value, and writes the frame's bytes into a buffer that is wiped when it drops.OwnedFrame::from_buffer(crate/src/js.rs:62) moves that buffer into the engine's type without a copy. The call parses the bytes once to check them.OneValue::scalar(crate/src/value.rs:53-59) refuses an array or an object, and wraps the frame. The engine's opaque encrypt takes only aScalartype, and a frame is not one.seal(crate/src/cipher.rs:389-405) encrypts on napi's runtime, off the JavaScript thread.
On fc5c851, step 5 built a second type, ValueFrame, from the bridge's bytes. Merge 85c1fc8 replaced that type with OwnedFrame::from_buffer.
Why there is a frame at all: the addon runs the engine's future with napi's spawn_future_with_callback. spawn_future_with_callback needs a Send + 'static future (crate/src/cipher.rs:10-12). An Unknown belongs to the JavaScript thread. So the value is copied out of JavaScript before the key request. The frame is that copy.
The frame is also the engine's own type for a value whose type is known only at run time. So no second conversion is needed.
What napi does: napi gives the type checks and the scalar reads. The bridge uses them: get_type, is_array, is_date, is_typedarray, f64, bool, BigInt, and Uint8ArraySlice (value-napi/src/js_ref.rs:178-282). The napi version in Cargo.lock is 3.16.2.
What napi cannot do: napi has no conversion into the engine's value model. The one conversion of a whole value that napi has is to serde_json::Value (napi-3.16.2/src/bindgen_runtime/js_values/serde.rs:151). That conversion breaks the SDK's rules in five ways:
- A whole
numberin theu32ori32range becomes an integer, and any othernumbera float (serde.rs:375-391). In the SDK, anumberis always a 64-bit float. - A
bigintthat does not fit 64 bits becomes a string, with no error (serde.rs:202-217). - A
Date, aBuffer, aUint8Array, and theRc*classes are read as plain objects (serde.rs:170-197). - An array element is read with
napi_get_element(serde.rs:186). So a value on a pollutedArray.prototypefills a hole. - To decrypt, napi sets each member with
napi_set_property(serde.rs:110). That call runs a setter on a pollutedObject.prototype. A member named__proto__sets the prototype.
napi's typed reads are not safe either. napi reads an i64 with napi_get_value_int64 (number.rs:70), and that call drops a fraction. So the bridge reads every number as an f64.
What still looks unnecessary:
OneValue. The pull request feat(stack-encrypt)!: encrypt and decrypt one value known only at run time, and bound the typed decrypt to a scalar #2011 deletes it.sealthen calls the engine'sdynamic::value::encryptfor each frame, and merges the calls withPending::all.- The parse in step 5. The bridge and the engine use one
vitaminc-aeadcrate (Cargo.toml:27-29). So the bridge could returnOwnedFrame::of(JsRef).OwnedFrame::ofwrites the frame without a second parse (packages/vitaminc-aead/src/frame/owned.rs:65-67). Therecipher_js::valueerror would go too. - The kind argument of
Ciphertext.fromBytes. The addon reads{ name }with the whole walk and the frame's serde (crate/src/ciphertext.rs:163-166). A property read would do. - The UUID check in
js::read. The pull request feat(recipher-js): encrypt a VcUuid as the engine's UUID #1996 removes it.
Decrypt converts once too. The engine decrypts into an OwnedFrame, and JsBuilder::build builds the JavaScript value (crate/src/js.rs:145-147).
| /// Makes a JSON document to encrypt as one ciphertext. The document is a | ||
| /// plain object, an array, text, a number, a `bigint`, a boolean or `null`, | ||
| /// nested at most 127 levels. | ||
| /// | ||
| /// Give an integer outside a `number`'s safe range as a `bigint`, within 64 | ||
| /// bits. The safe range is at most 2^53 - 1 from zero. A whole `number` | ||
| /// between 2^53 and 2^64 from zero is refused, because the caller probably | ||
| /// meant an integer. | ||
| /// | ||
| /// `json(..)` reads the document now. `json(..)` never throws: `encrypt` | ||
| /// returns an `Err` for a document that cannot be encrypted. |
There was a problem hiding this comment.
Included an example here. I can't reason about how this would be used.
There was a problem hiding this comment.
Partly. json(..) has an example now, in the Rust doc (crate/src/json.rs:117-124) and in README.md:104-112. napi copies the Rust doc to native.d.ts:245-253.
That example shows a bigint round trip. The example does not show the case this comment was on. The case is a large whole number given as a number, and json(..) refuses that number.
Proposed text, for the README's JSON section, the Rust doc, and the TypeScript doc of json (src/values.ts:156-177):
A whole
numberfrom2^53up to2^64may not have the digits you wrote, sojson(..)refuses it. Give the integer as abigint:// JSON.parse reads 9007199254740993 as 9007199254740992. const parsed = JSON.parse('{"id": 9007199254740993}') const refused = await keyset.encrypt(json(parsed)) refused.err()?.code // 'recipher_js::not_json' const sealed = (await keyset.encrypt(json({ id: 9007199254740993n }))).unwrap() const opened = (await cipher.decrypt(sealed)).unwrap() // { id: 9007199254740993n }
Each line matches the code and the tests: value-napi/src/scalar.rs:139-152, and __tests__/addon/values.test.ts:363-386 and :406-414. The example itself has not been run.
…hen it is built The README told the reader to wrap a plain object in `json(..)`, as if that were the only form. The SDK's design gives the caller two: a JSON document, or the engine's opaque format for a whole object. `opaque(..)` is not built yet, so `json(..)` is the one that works today. The README and the values module now say why an object is refused, name both forms, and say which one exists.
The JavaScript rules for a JSON document were in the addon, as a sink that turned a frame into a `serde_json::Value` and a walk that turned one back. They are a value mapping, so they belong in the value bridge. This commit adds them there. The addon moves to them in the next one. Encrypting: `JsRef::to_json(max_depth)` walks a JavaScript value and writes the text of a JSON document. - The walk is the bridge's own, with a second mode that reads only what a document holds. So holes, getters that throw, unpaired surrogates, reserved property names and objects that are not plain are refused as they are for any value. - A whole `number` within 2^53 - 1 of zero is written as an integer, as `JSON.stringify` writes it. napi-rs's `serde_json` conversion writes a whole number above 2^32 as a float (`5000000000.0`), which Rust's `serde_json` and Go's `encoding/json` refuse for an integer field. - A whole `number` from 2^53 up to 2^64 is refused: its digits may not be the ones written. A `bigint` is its exact digits within 64 bits, and refused outside them by one check, whatever its size. - `undefined`, a number that is not finite, bytes, a `Date` and a wrapper class instance are refused as `recipher_js::not_json`, with a message that names the kind of value and no part of it. - The text goes straight into a `vitaminc_protected::Buffer`, which wipes each allocation it outgrows. No tree of the document is built. - The depth limit is the caller's: the bridge has no second constant. `Refusal::TooDeep` now carries its limit, so its message states the limit that applied. Decrypting: `JsBuilder::build_json(env, &Value)` builds the JavaScript value. Each scalar goes through napi-rs's own conversion: an integer in the safe range is a `number`, any other a `bigint`, a float a `number`. Arrays and objects are built here from own data properties, with the reserved names refused. napi-rs assigns each member, so a member named `__proto__` becomes the object's prototype and a setter on a polluted prototype receives the decrypted value. `tests/json.cjs` checks every rule in a live Node, and pins what napi-rs's conversion does in both directions, so a change in it shows. The walk's recursive functions hold less than before: reading a scalar and choosing an object's shape moved into helpers, so the second mode costs a nested level no more stack. A debug build walks the test suite's deepest values at the same stack size as before. Cargo.lock: `recipher-value-napi` gains `serde` and `serde_json`, which the workspace already resolves. The test addon's lock gains the same.
…ridge and the engine
The addon's `json.rs` held 580 lines that converted a frame to a
`serde_json::Value` and back, with the JavaScript number rules. The
engine already takes a document, as `JsonPlaintext`, and the value
bridge now reads and builds one. So the addon converts nothing.
Encrypting: `json(..)` asks the bridge for the document's JSON text
(`JsRef::to_json`) and keeps the text in the `Json`, in a buffer that is
wiped when it drops. `encrypt` gives the text to the engine's parser
(`JsonPlaintext::parse`), and the engine encrypts the document through
the same single-value path as before. Text is the hand-off because the
engine reads a document from text in every other SDK.
Decrypting: the worker gives the decrypted text to the engine's parser
(`read_json`), and the JavaScript thread asks the bridge to build the
document (`JsBuilder::build_json`). A decrypted value is now an `Opened`:
a frame, or a document.
What is gone: the `ToJson` sink and its `Out` trait, `FromJson`, `walk`,
`number_of`, the `float` and `integer` rules, and the addon's
`NotJson` and `JsonTooDeep` errors. The bridge reports both refusals,
under the same codes.
`Json::of` has an example, and says why it returns an `Option` of a
`Result`. `json(..)` has an example too, and its doc says what a caller
sees: the number rules in both directions, that `json({ a: 5n })`
decrypts as `{ a: 5 }`, and that an object's members come back sorted
by key, which is how the engine stores them.
The addon suite checks each rule through `keyset.encrypt(json(..))`. It
reads the stored text back, so `json({ n: 5000000000 })` is pinned as
`{"n":5000000000}`, the text a Go or a Rust reader takes as an integer.
`native.d.ts` is regenerated for the `json` doc comment.
`js::elements` read every index of the array with `get_element` and never asked whether the index was an own property. A hole has none, so the read went to the prototype chain. With `Array.prototype[1] = 'injected'`, `keyset.encrypt(['a', , 'b'])` was `Ok` and decrypted to `['a', 'injected', 'b']`. In the same way, `cipher.decrypt([ct, , ct])` decrypted a ciphertext the caller never passed. With no pollution a hole was `recipher_js::undefined` or `not_a_ciphertext`, not the `sparse_array` refusal the README lists. Each index is now checked with `has_own_property` before it is read, as the bridge's walk does for an array inside a value, and a hole is `recipher_js::sparse_array`. The result is no longer allocated from the array's length, which JavaScript reports and `new Array(2 ** 32 - 1)` makes for free. Two tests fail without the fix: one for a hole, to encrypt and to decrypt, and one for a hole with a polluted `Array.prototype`.
…exports
`kind_of` accepted any name the engine's `ValueKind` parses, except
`array` and `object`. So `Ciphertext.fromBytes(bytes, { name: 'uuid' })`
was `Ok`, though `kinds` has no UUID kind and the method's doc promises
`recipher_js::not_a_kind`. Every decrypt of that ciphertext then failed
with `recipher_js::opened_type`.
The addon now lists the kinds a stored ciphertext can be read as, and
refuses any other name. A kind the engine adds later is refused until
the package exports it.
A test in the addon suite reads a ciphertext as every kind in `kinds`,
and checks that the engine's other names are refused, so the Rust list
and the TypeScript `kinds` cannot drift apart unseen.
`an_error_of_the_sdks_own_has_its_code_message_and_help` once asserted the help of `not_a_ciphertext`, and now asserts that of `undefined`. So no test checked the help of `not_a_ciphertext`, `uuid`, `not_a_scalar`, `plain_object`, `no_testing`, `no_result` or `build_value`. A help could be dropped or reworded with no test failing. A new test checks the help of every variant: the text for a variant that has help, and none for a variant that leaves the caller nothing to do. Its match has no wildcard, so a new variant does not compile without an entry.
… form today Three doc comments said that Rust and Go write the same bytes as `keyset.encrypt` here. Go has no call that encrypts one value on its own, so the claim was true of Rust only. Each now names what does write that form: Rust's `keyset.encrypt`. The `Scalar` trait is `vitaminc-aead`'s, so the doc on `OneValue` names the crate. `native.d.ts` is regenerated for the `Ciphertext` class doc.
The README's JSON section and the TypeScript docs described only part of
what `json(..)` does, and only on the way in.
They now give the rules in both directions, in one table: which numbers
are stored as an integer, which as a float, which are refused, and what
each decrypts as. They also say three things a caller would otherwise
find out by surprise:
- a whole number such as `5000000000` is stored as an integer, so code
in Rust or Go can read it into an integer field;
- `json({ a: 5n })` decrypts as `{ a: 5 }`, because an integer in the
safe range comes back as a `number`;
- a decrypted object lists its members sorted by key, because that is
how the engine stores them.
AGENTS.md says the bridge converts JSON documents and the addon's
`json.rs` holds only the `Json` class, and that a wrapper class's
constructor throws for an argument that is not a string.
…builds `JsBuilder::build_json` stops at the bridge's depth limit, so a document that no parser has bounded cannot overflow the stack. No test reached that check: the test addon parsed its documents with `serde_json`, which stops at 127 levels, below the limit of 128. A mutation run over the bridge's new code showed it. Four mutants of `json_to_js` survived: the comparison with the limit, twice, and the step to the next level, for an array and for an object. The test addon now builds a nested document itself, and the Node suite builds 128 levels and is refused at 129, for arrays and for objects. All four mutants are caught.
The rename left the article of the old name.
|
The review is addressed in 14 new commits (head c378520), and every thread has a reply. The changes are merged up into #1776 and #1996. What changed
Choices to review
Not done
Checks (Rust 1.94.1, Node 24.1.0): fmt, clippy, One thing to check in CI: |
Rewrite the comments, doc comments and Markdown that the values work added, so that each passes the plain-language checker. No code changes. - One idea in each sentence, and lists for parallel cases. - Each term is defined where a doc first uses it: engine, value bridge, walk, frame, kind, wrapper class, safe range. - Things have literal verbs: a document "contains" a value. - The value bridge's README is rewritten in full, with headings for the safety rules. - `native.d.ts` is regenerated, because the build copies the doc comments of the `#[napi]` items into it. - The addon's crate docs no longer link to the private `js` module, so `cargo doc` with warnings denied passes.
A TypeScript developer reads these messages without knowing the engine. The messages said "seal", "open", "hold", and "takes". The README says "encrypt", "decrypt", "contain", and "accept", so the messages now use those words. Each message says what was wrong with the value that was passed, and the help says what to do. No error code, error field, or refusal changes. Only the text changes, with the tests and docs that quote it. - The addon's errors say "encrypt" and "decrypt". `not_a_scalar` and `plain_object` say that the value cannot be encrypted as one value, and the help says what `json(..)` does. - `not_a_kind` now states the fault in the message. The rule that was the message is now the help. - `opened_type` names the kind that the caller gave, in backticks. No message names the kind that a value decrypted as. - A refused JSON value reads "a JSON document cannot contain ...". The messages for a large `number` and for a typed value end with a sentence that says what to pass. - A wrapper class's constructor throws "RcDate accepts only a string". The addon's class and the stand-in throw the same text.
|
This replies to review 6058012745. Status of the review on too many layers, at 1cf2f55. Point 3 is done. Point 4 waits on #2011. Points 1 and 2 are not done, and the stand-ins need your decision.
Stand-ins: your decision. The stand-ins are all still here: Scope: besides the array overloads, the kind on |
|
This replies to review 6030302742. Status of the automated review of 23 November, at 1cf2f55. Errors no longer have a These findings are fixed:
These findings are partly fixed:
|
…efused The engine accepts a UUID now. This version of the SDK still refuses an `RcUuid`, because it has no kind and no TypeScript type for a UUID yet. The README, two doc comments, a test, and the error message said that the engine has no UUID type. Those places now say that this version of the SDK does not encrypt a UUID yet. The test now checks the new message. `encrypt` and `decrypt` changed shape since the first addon build, but the binding interface number was still 1. So the TypeScript would load an older addon build and fail later, on a call. The number is now 2 in the crate and in `src/binding.ts`. The comments on both say what the number is for, and when to change it.
The TypeScript doc of `json` said a `bigint` is stored "within 64 bits". The range is from -(2n ** 63n) to 2n ** 64n - 1n, which no single 64-bit type holds, and the doc did not say a `bigint` outside it is refused. The Rust doc and the README already give the range. This makes the TypeScript doc match them.
|
This replies to the two findings in the body of review 6094305185. An earlier comment listed both as not done.
|
…gint json() refused a whole number from 2^53 up to 2^64 with a message that says to pass a bigint. Below -2^63 that advice is wrong. A bigint that size is outside the 64-bit range, so json() refuses it too. The integer has no exact form in a JSON document. A whole number below -2^63 and above -2^64 now has its own refusal, NoJsonForm::NoExactForm, under the same recipher_js::not_json code. The refusal says the integer has no exact form. The message does not ask for a bigint. From -2^53 down to -2^63 the message still asks for one, since a bigint of that size is accepted. The json() docs, the README files, and the type docs now state both rules. The tests cover these values: - the first number below -2^63, -1e19, and the last number above -2^64; - -2^63, as a number and as a bigint; - -2^64, as a float.
The second review of #2019 found the plan out of step with the code. - The wrapper classes are RcDate, RcTimestamp, RcDecimal, and RcUuid in #1775, #1776, and #1996. The plan used vitaminc's Vc names. The plan now uses the Rc names, and says once that #1775 renamed them. - The JSON number rules are now one table, with a row for each range of whole numbers. Each range includes both ends. The table shows the new refusal below -2^63. That refusal says the integer has no exact form. The plan also says that NaN and the infinities are refused. - The round trip of 2^64 - 1 is tested on the native build only. The plan now names that test, and says the wasm build is planned. - The UUID cell no longer repeats the refusal before #1996. - The header now gives the status. Step 1 is built. The next steps are in open pull requests.
|
I pushed 5c78ecf to this branch. Why: before this commit, Changes:
Tests:
Checks run: #1776 and #1996 are stacked on this branch, so they need this commit merged in. |
This brings in two commits from #1775. The first gives the bigint range in the json() docs. The second refuses a whole number below -2^63 and above -2^64 with its own message, instead of asking for a bigint. The merge had no conflicts.
next removed the addon's OneValue and sent its string-only encrypt through the engine's dynamic::value::encrypt. This branch encrypts every value type, so its cipher.rs, engine_tests.rs, value.rs and Cargo.toml keep this branch's side here, and OneValue stays for now. The next commit removes OneValue and uses dynamic::value on this branch too.
…declared kind
next removed the addon's OneValue wrapper. The engine's
dynamic::value::encrypt now encrypts the one scalar in a frame. This
commit removes this branch's OneValue too, and sends every single-value
encrypt through dynamic::value::encrypt. A json(..) value goes in as its
JSON text, with the declared kind json. The engine parses the text into
the JsonPlaintext it encrypts, so the stored form does not change.
keyset.encrypt takes a second argument, { kind }, with a kind from
kinds. The addon passes the kind to the engine. The engine converts a
value to the kind when the conversion is exact, as a record write does.
The ciphertext then decrypts as that kind: 34 declared as uint64 decrypts
as 34n. For an array of values, the kind applies to each value.
The kind is an options object, not a positional argument, so that a
context can be added later under its own name. Neither can then be
passed in the other's place. The options refuse any key but kind, with
recipher_js::options, so an option that this version does not have is
never ignored.
What changes for a JavaScript caller:
- A lone null is now refused, with the new code recipher_js::null. The
error's help says to store a database NULL, or to declare the kind of a
fixed-width type. The engine refuses a null, because a ciphertext
contains one value.
- A null declared as a fixed-width kind is refused today as well. Issue
#2023 changes the engine to encrypt it as a padded typed null. A Rust
test and a JavaScript test check today's refusal, and name #2023.
- The TypeScript types accept null only with a fixed-width kind. A null
with no options still type-checks, and fails when the call runs.
- json(..) declared as another kind, or kinds.json declared for a value
that is not a json(..), is refused with recipher_js::json_kind.
- A second argument that is not { kind } is refused. Before, a second
argument was ignored.
- recipher_js::not_sealed is gone. The engine reports a JSON text it
cannot parse with its own code. The bridge writes no such text.
- The codes for an array inside an array (recipher_js::not_a_scalar)
and a plain object (recipher_js::plain_object) are the same. The
addon now maps them from the engine's refusal.
…l_value feat/recipher-js-records already uses recipher_js::null for a null mode that the engine does not have. The two errors are about different things, so a lone null now has its own code, recipher_js::null_value.
Summary
Closes #1812
This PR lets
@cipherstash/recipherencrypt every value type in the value bridge's mapping, arrays of values, and JSON documents. A value's type decides how it is encrypted; no call names a type. A ciphertext read back from stored bytes can be given a kind (a value type, such askinds.string), so a stored JSON document decrypts as the document and not as its text.It follows #1774's design: every native method builds its
Resultin Rust, and the signatures are written on the Rust methods, so the generatednative.d.tsis the public type. There is no TypeScript layer that wraps the native methods.The package is private and not published, so there is no changeset.
Changes
Values.
keyset.encrypt(value)takes astring,boolean,number(a float),bigint(an integer at the narrowest width that holds it),Uint8ArrayorBuffer,Date,VcTimestamp,VcDate,VcDecimal,null, or aJson. It resolves to aResultof aCiphertext<T>, whereTis the type it decrypts to. The addon exports the bridge's wrapper classes, and the package re-exports them.Arrays. An array in gives an array out, in the same order, through the engine's collection path: one key request each way. If one element is refused, the whole array is an
Err, before any request.JSON documents.
json(document)is a native function that returns a nativeJson. It reads the document when it is called, and never throws. The conversion is incrate/src/json.rs:number's safe range is abigint, within the 64-bit range the engine's parser reads;numberbetween 2^53 and 2^64 is refused, because an integer was likely meant; any other finitenumber, such as1e20, is a float;recipher_js::too_deep;Zeroizinguntil it is in the object, so a refused member leaves no unwiped copy.Reading stored bytes as a kind.
Ciphertext.fromBytes(bytes, kinds.string)is typedCiphertext<string>. Decrypting it refuses a value encrypted as another type (recipher_js::opened_type). An integer kind takes an integer of any width that fits.kinds.jsondecrypts the text as a document.Ciphertext.fromBytes(bytes)with no kind is aCiphertext<OpenedScalar>: it can decrypt to any scalar.Signatures. The new overloads are
ts_typestrings on the Rust methods, one per line:encryptanddecrypton an array (crate/src/cipher.rs), andfromBytes<K extends Kind>(bytes, kind)(crate/src/ciphertext.rs).jsontakes aJsonValue.native-header.d.tsimports the types they name, makesCiphertext's defaultOpenedScalar, and marksJsonso no other object type-checks as one.Where the value types live. The types the signatures name (
Value,Opened,OpenedScalar,JsonValue, the wrapper interfaces) are insrc/value-types.ts, which imports nothing.native.d.tsimports them, and a module that loaded the addon would make the declarations import themselves, which the declaration bundler cannot build.src/values.tskeeps the runtime part: the wrapper classes andjson, with stand-ins.Errors. Each new refusal is a variant of the SDK's error enum, with its own code:
recipher_js::undefined,uuid,not_a_scalar,plain_object,not_json,too_deep,not_sealed,not_a_kind,opened_typeandnot_a_document. The skeleton'srecipher_js::not_a_stringis gone. The bridge's refusals keep the bridge's codes.recipher_js::reserved_keyreaches the caller on decrypt too, through the bridge'sRefusal.Decrypting through
open_in. The array and kind decrypt path runs through #1774'sopen_in, so keyset confinement stays in one place.AGENTS.md. The recipher-js entry now names theJsonclass, and says thatsrc/kinds.tsandsrc/value-types.tshold the types the generated signatures name and must never load the addon.Missing build. Without the addon, the wrapper classes and
jsonare stand-ins that construct normally, and every call resolves to the load error.The binding interface number stays 1: nothing is released.
Verification
Run locally on macOS (arm64), Rust 1.94.1, Node 24, pnpm 10.33.2, at this PR's head:
cargo fmt --all --check: clean.cargo test --locked --all-features:recipher-js31 unit tests and 2 boundary tests passed;recipher-value-napi33 unit tests andtests/node.rspassed.cargo clippy --locked --all-targets --all-features -- -D warnings: clean.cargo fmt --checkandcargo clippy --locked --target-dir target/napi-test-addon -- -D warningsby its manifest: clean.build:debug:native.d.tsregenerated and committed; the build leaves no other change.test:addon: 57 passed.test(vitest, thentscwith the type tests): 26 passed, typecheck clean.check-auth-npm-changeset, which cannot load@changesets/parsein the local sandbox.tests-workflow-gate,recipher-js-lock-parityandworkflow-turbo-build-depspass.The Rust tests check that the engine and the SDK each decrypt what the other encrypted, for every type, and that an array is one key request each way. Not run: anything against a live ZeroKMS. CI results are in the checks.
Review notes
type-tests/native.tschecked thatCiphertextwith no type named isCiphertext<string>. It is nowCiphertext<OpenedScalar>, because a ciphertext read from stored bytes with no kind can decrypt to any scalar. The test also checks thatJsonandjsonare the generated ones.recipher-value-napilost its mutation, CRAP and dependency checks in the move from vitaminc, and Biome skips it — restore them and add fuzzing #1797 tracks the bridge's fuzz targets.opaque(..)is not here. The engine has no entry point from a frame to its storage-profile bytes.VcUuidis refused withrecipher_js::uuid. The engine's value model has no UUID type.kinds.jsonreads it as a document.1e20encrypts again.recipher_js::reserved_keyhas the same code on encrypt and decrypt. Only the call that failed says which.OneValueincrate/src/value.rsis widened here to a scalar or a JSON document. The engine's own single-value frame will replace it later.Related